<?php 
class ControllerCart extends Controller {
	function index() {
		$cart     =& $this->locator->get('cart');
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$customer =& $this->locator->get('customer');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$module   =& $this->locator->get('module');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$shipping =& $this->locator->get('shipping');
		$tax      =& $this->locator->get('tax');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');
        $session  =& $this->locator->get('session');
		
    	if ($request->isPost() && $request->has('task', 'post')) {
      		if ($request->gethtml('product_id', 'post')) {
        		$cart->add($request->gethtml('product_id', 'post'), ($request->gethtml('quantity', 'post'))?$request->gethtml('quantity', 'post'):'1', $request->gethtml('option', 'post'));
      		}
            
            //See http://code.google.com/p/open-cart/issues/detail?id=68
      		if (@$request->gethtml('quantity', 'post') && is_array($request->gethtml('quantity', 'post'))) {
                foreach ($request->gethtml('quantity', 'post') as $key => $value) {
                    $session->set('min_qty_error['.$key.']', '0');
                    $session->set('line_min_error['.$key.']', '0');
                    if ($request->gethtml('min_qty', 'post') != null) {
                        foreach ($request->gethtml('min_qty', 'post') as $k => $v) {
                            if ($k == $key) {
                                if ($value != 0) {
                                    if ($value < $v) {
                                        $value = $v;
                                        $session->set('min_qty_error['.$key.']', '1');
                                        $session->set('line_min_error['.$key.']', '1');
                                    }
                                }
                                $cart->update($key, $value);
                            }
                        }
                    } else {
                        $cart->update($key, $value);
                    }
                }
            }

      		if ($request->gethtml('remove', 'post')) {
	    		foreach (array_keys($request->gethtml('remove', 'post')) as $key) {
          			$cart->remove($key);
				}
      		}
      
	  		$response->redirect($url->ssl('cart'));
    	}

		$language->load('controller/cart.php');

    	$template->set('title', $language->get('heading_title'));
	
    	if ($cart->hasProducts()) {
      		$view = $this->locator->create('template');

			$view->set('tpl', $template);
			
      		$view->set('heading_title', $language->get('heading_title'));

      		$view->set('text_subtotal', $language->get('text_subtotal'));
            $view->set('text_stock_ind', $language->get('text_stock_ind'));
            $view->set('text_min_qty_ind', $language->get('text_min_qty_ind'));
            
      		$view->set('column_remove', $language->get('column_remove'));
      		$view->set('column_image', $language->get('column_image'));
      		$view->set('column_name', $language->get('column_name'));
      		$view->set('column_model', $language->get('column_model'));
      		$view->set('column_quantity', $language->get('column_quantity'));
			$view->set('column_price', $language->get('column_price'));
      		$view->set('column_total', $language->get('column_total'));
            $view->set('column_min_qty', $language->get('column_min_qty'));

      		$view->set('button_update', $language->get('button_update'));
      		$view->set('button_shopping', $language->get('button_shopping'));
      		$view->set('button_checkout', $language->get('button_checkout'));

      		$view->set('error', ((!$cart->hasStock()) && ($config->get('config_stock_check')) ? $language->get('error_stock') : NULL));
      		$view->set('stock_check', $config->get('config_stock_check'));
      		$view->set('action', $url->href('cart'));

      		$product_data = array();

     		foreach ($cart->getProducts() as $result) {
        		$option_data = array();

        		foreach ($result['option'] as $option) {
          			$option_data[] = array(
            			'name'  => $option['name'],
            			'value' => $option['value'],
          			);
        		}
                
                // Minimum Order Verification
                $min_qty_error = '0';
                $line_min_error = '0';
                if ($result['quantity'] != 0) {
                    if ($result['quantity'] < $result['min_qty']) {
                        $result['quantity'] = $result['min_qty'];
                        $min_qty_error = '1';
                        $line_min_error = '1';
                    }
                }
                
        		$product_data[] = array(
          			'key'           => $result['key'],
          			'name'          => $result['name'],
          			'model'         => $result['model'],
          			'thumb'         => $image->resize($result['image'], 50, 50),
          			'option'        => $option_data,
          			'quantity'      => $result['quantity'],
                    'min_qty'       => $result['min_qty'],
                    'min_qty_error' => ($line_min_error || $session->get('line_min_error['.$result['key'].']') ? '1' : '0'),
          			'stock'         => $result['stock'],
					'price'         => $currency->format($tax->calculate($result['price'], $result['tax_class_id'], $config->get('config_tax'))),
          			'discount'      => ($result['discount'] ? $currency->format($tax->calculate($result['price'] - $result['discount'], $result['tax_class_id'], $config->get('config_tax'))) : NULL),
					'total'         => $currency->format($tax->calculate($result['total'], $result['tax_class_id'], $config->get('config_tax'))),
					'href'          => $url->href('product', FALSE, array('product_id' => $result['product_id']))
        		);
                
                if ($min_qty_error == '1' || $session->get('min_qty_error['.$result['key'].']')) {
                    $view->set('error', $language->get('error_min_qty'));
                    $session->set('min_qty_error['.$result['key'].']', '0');
                    $session->set('line_min_error['.$result['key'].']', '0');
                }
                    
      		}

      		$view->set('products', $product_data);
            
     		$view->set('subtotal', $currency->format($cart->getSubtotal()));

            $view->set('weight', $cart->formatWeight($cart->getWeight()));
            
            $view->set('text_cart_weight', $language->get('text_cart_weight'));
            
      		$view->set('continue', $url->href('home'));

      		$view->set('checkout', $url->ssl('checkout_shipping'));

	  		$template->set('content', $view->fetch('content/cart.tpl'));
	  
	  		$template->set($module->fetch());

      		$response->set($template->fetch('layout.tpl'));
    	} else {
      		$view = $this->locator->create('template');

      		$view->set('heading_title', $language->get('heading_title'));

      		$view->set('text_error', $language->get('text_error'));

      		$view->set('button_continue', $language->get('button_continue'));

      		$view->set('continue', $url->href('home'));

	  		$template->set('content', $view->fetch('content/error.tpl'));
	  
	  		$template->set($module->fetch());

      		$response->set($template->fetch('layout.tpl'));
    	}
  	}
	
	// Add function for add from anywhere (product page, home page, etc)
	function addAjax() {
		$cart     	=& $this->locator->get('cart');
		$config   	=& $this->locator->get('config');
		$currency 	=& $this->locator->get('currency');
		$language 	=& $this->locator->get('language');
		$request  	=& $this->locator->get('request');
		$response 	=& $this->locator->get('response');
		$url		=& $this->locator->get('url');
		$template	=& $this->locator->get('template');
		
		$product_id = $request->get('product_id');
		$options = str_replace(',', '.', $request->get('options'));
		if (!$options) {
      		$key = $product_id;
    	} else {
      		//$key = $product_id . ':' . implode('.', $options);
      		$key = $product_id . ':' . $options;
    	}
    	
		if ($request->has('quantity')) {
			$quantity = $request->get('quantity');
		} else {
			$quantity = '1';
		}
		
		if ($key && $quantity){
			$cart->addAjax($key, $quantity);
		}
		
		$language->load('extension/module/cart.php');
		
		$view = $this->locator->create('template');
		$view->set('tpl', $template);
		$view->set('heading_title', $language->get('heading_title'));
		$view->set('text_subtotal', $language->get('text_subtotal'));
		$view->set('text_view_cart', $language->get('text_view_cart'));
		$view->set('view_cart', $url->href('cart'));
		$view->set('ajaxadd', $config->get('config_ajaxadd_product'));
		
		$product_data = array();
		foreach ($cart->getProducts() as $result)
		{
			$product_data[] = array(
				'href'     => $url->href('product', false, array('product_id' => $result['product_id'])),
				'name'     => $result['name'],
				'quantity' => $result['quantity']
			);
		}

		$view->set('products', $product_data);
		$view->set('subtotal', $currency->format($cart->getsubTotal()));
		$view->set('text_empty', $language->get('text_empty'));
		$config->set('suppress_parse_time', true);
		
		$output = $view->fetch('module/cart.tpl');
		$output = trim($output, '<li id="module_cart">');
		$output = trim($output, '</li>');
		$response->set($output);
	}
}
?>
